import { asyncRoutes, constantRoutes } from 'lxsh-auth-web-pc/src/router'
import router,{baseRouter,addRouters} from 'hhlt-vue/src/router'
import Layout from 'lxsh-layout/src/layout/index.vue'
import LayoutFull from 'lxsh-layout/src/layoutFull/index.vue'
import { RouteRecordRaw } from 'vue-router'

/**
 * Use meta.role to determine if the current user has permission
 * @param menus
 * @param route
 */
function hasPermission(menus:any, route:any) {

  if (route.meta && route.meta.menuValue) {

    return menus.some((menu:any) => {

      if(menu.menuValue){

        return route.meta.menuValue === menu.menuValue
      }

      return false
    })
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes async  Routes
 * @param menus
 */
export function filterAsyncRoutes(routes:any, menus:any) {
  const res:any = []

  routes.forEach((route: any) => {
    const tmp = { ...route }
    if (hasPermission(menus, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menus)
      }
      res.push(tmp)
    }
  })

  return res
}

/**
 * 构建路由
 * @param {*} menus
 */
export function buildRoutes(menus:any){

  var route:any = []
  menus.forEach((menu: { data: { menuType: string }; children: any[] }) => {

    if(menu.data.menuType === '0'){//如果是系统此处不展示
      debugger
      if(menu.children && menu.children.length > 0){

        menu.children.forEach(child => {
          var buidChildRoutes = buildRoute(child)
          if(Array.isArray(buidChildRoutes)){

            route = route.concat(buidChildRoutes)

          } else {

            route.push(buidChildRoutes)

          }

        })
      }
    }
    // route.push(buildRoute(menu))
  })

  return route
}

// export function loadPageByRoutePath(path) { // views文件夹下的Home组件，传入的格式为 'Home'
//   return function (resolve) {
//     require([`@/views/${path}.vue`], resolve);
//   };
// }

/**
 * 构建路由
 * @param {*} menus
 */
export function buildRoute(menu:any){
    debugger
    //如果是按钮级别的菜单直接返回，不需要路由跳转
    if(menu.data.menuType === '3'){

      return
    }
    //如果不是是菜单，或内部菜单，或内部页面则判断其子路由是否是这几种类型，即菜单表中配置未内部菜单的项目不具备路由跳转的功能，无需在构建路由时对它进行构建
    if(!(menu.data.menuType === '0' || menu.data.menuType === '1' || menu.data.menuType === '2' || menu.data.menuType === '3' || menu.data.menuType === '10'
    || menu.data.menuType === '30' || menu.data.menuType === '50')){

      if(menu.children && menu.children.length > 0){
          var childrenRouteList:any = []
          for(var i=0;i<menu.children.length;i++){

            var childrenRoute:any = buildRoute(menu.children[i])

            if(childrenRoute){
              if(Array.isArray(childrenRoute)){

                childrenRouteList = childrenRouteList.concat(childrenRoute)

              } else {

                childrenRouteList.push(childrenRoute)

              }
            }
          }

          return childrenRouteList
      }
    }
    var route:RouteRecordRaw = {
      path: menu.data.menuUrl,
      component: process.env.VUE_APP_OPEN_FULL_SCREEN === '0' ? LayoutFull : Layout,
      name: menu.data.menuCode ? menu.data.menuCode : menu.data.id,
      meta: { title: menu.data.menuName, icon: menu.data.icon, menuType:menu.data.menuType},
      children:[]
    }
    if(menu.data.menuType === '1'){

    } else if(menu.data.menuType === '2'){
      //如果是二级菜单

      if(menu.data.pagePath){

        if(menu.data.systemCode == "lxsh-auth-web-pc"){

        	route.component = () => require(`lxsh-auth-web-pc/src/views/${menu.data.pagePath}`);
        } else if(menu.data.systemCode == "lxsh-cer-web-pc"){
          debugger
        	route.component = () => require(`lxsh-cer-web-pc/src/views/${menu.data.pagePath}`);
        } else if(menu.data.systemCode == "lxsh-basedata-web-pc"){

          route.component = () => require(`lxsh-basedata-web-pc/src/views/${menu.data.pagePath}`);
        }
      } else {
        if(route.meta){

          route.meta.hidden = true
        }

      }

    } else {

      if(menu.data.pagePath){

        if(menu.data.systemCode == "lxsh-auth-web-pc"){

        	route.component = () => require(`lxsh-auth-web-pc/src/views/${menu.data.pagePath}`);
        } else if(menu.data.systemCode == "lxsh-cer-web-pc"){

        	route.component = () => require(`lxsh-cer-web-pc/src/views/${menu.data.pagePath}`);
        } else if(menu.data.systemCode == "lxsh-basedata-web-pc"){

          route.component = () => require(`lxsh-basedata-web-pc/src/views/${menu.data.pagePath}`);
        }
      }

      if(route.meta){

        route.meta.hidden = true
      }
    }

    if(menu.children && menu.children.length > 0){

      var childInnerPage:any = undefined

      menu.children.forEach((child: { data: { menuType: string } }) => {

         var childrenRoute = buildRoute(child)

         if(childrenRoute && route.children){

          if(Array.isArray(childrenRoute)){

            route.children = route.children.concat(childrenRoute)

          } else {

            route.children.push(childrenRoute)

          }

           // route.children.push(childrenRoute)
         }

         if(child.data.menuType === '50'){

           childInnerPage = child
         }

      })

      if(childInnerPage){

        route.redirect = childInnerPage.data.menuUrl

      }
    // }
    // if(parentRoute && parentRoute.children){

    //   parentRoute.children.push(route)
    // }
  }

  return route

}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state:any, routes:any) => {
    addRouters(routes)
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }:any, menus:any) {
    console.log("generateRoutes 开始执行");

    return new Promise(resolve => {
      let accessedRoutes
      if (menus.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {

        accessedRoutes = buildRoutes(menus)
        // accessedRoutes =filterAsyncRoutes(asyncRoutes, menus)
      }

      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
